<template>
    <el-row class="login-container" justify="center" :align="'middle'">
        <el-card style="max-width: 480px;" >
            <template #header>
                <div class="card-header">
                    <img :src="imgUrl" alt="">
                </div>
            </template>
            <div class="jump-link">
                <el-link type="primary" @click="handleChange">{{ formType ? '返回登录' : '注册账号' }}</el-link>
            </div>
            <el-form
                ref="loginFormRef"
                style="max-width: 600px"
                :model="loginForm"
                :rules="rules"
            >
                <el-form-item prop="userName">
                    <el-input v-model="loginForm.userName" placeholder="手机号" :prefix-icon="UserFilled" clearable/>
                </el-form-item>
                <el-form-item prop="passWord">
                    <el-input v-model="loginForm.passWord" type="password" placeholder="密码" :prefix-icon="Lock" clearable/>
                </el-form-item>
                <el-form-item prop="validCode" v-if="formType">
                    <el-input v-model="loginForm.validCode" placeholder="验证码" :prefix-icon="Lock" clearable>
                        <template #append>
                            <el-button type="info" :disabled="countdown.disabled" @click="countdownChange">
                                {{ countdown.validText }}
                            </el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :style="{width: '100%'}" @click="submitForm(loginFormRef)">
                        {{ formType ? '注册' : '登录' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-row>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { getCode, userAuthentication, login } from '../../api';
import { ElMessage } from 'element-plus';
import {Lock, UserFilled} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';

const router = useRouter()

const imgUrl = new URL('/public/login-head.png', import.meta.url).href

// 切换表单 0登录 1注册
const formType = ref(0)
const handleChange = () => {
    formType.value = formType.value ? 0 : 1
}

// 表单数据
const loginForm = reactive({
    userName:'',
    passWord:'',
    validCode:''
})

// 验证码相关
const countdown = reactive({
    validText:'获取验证码',
    time: 60,
    disabled: false
})
const countdownChange = async () => {
    if(countdown.disabled) return

    // 手机号是否正确
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    if(!loginForm.userName || !phoneReg.test(loginForm.userName)){
        return ElMessage({
            message: '请输入正确的手机号',
            type: 'error',
        })
    }

    countdown.disabled = true
    const timer = setInterval(() => {
        if(countdown.time <= 0){
            countdown.time = 60
            countdown.validText = '获取验证码'
            countdown.disabled = false
            clearInterval(timer)
        }else{
            countdown.time -= 1
            countdown.validText = `剩余${countdown.time}秒`
        }
    }, 1000)

    // 获取验证码
    const data = await getCode({tel: loginForm.userName})
    if(data.code === 10000){
        ElMessage({
            message: data.msg,
            type: 'success'
        })
    }else{
        ElMessage.error(data.msg)
    }
}

const validateUserName = (rule, value, callback) => {
    // 手机号是否正确
    if(value === ''){
        callback(new Error('手机号不能为空'))
    }else{
        const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        phoneReg.test(value) ? callback() : callback(new Error('请输入正确的手机号'))
    }
}

const validatePassWord = (rule, value, callback) => {
    // 手机号是否正确
    if(value === ''){
        callback(new Error('密码不能为空'))
    }else{
        const pwdReg = /^[a-zA-Z0-9_-]{4,16}$/
        pwdReg.test(value) ? callback() : callback(new Error('请输入4-16位字符(数字、字母)'))
    }
}

// 表单校验
const rules = reactive({
    userName: [{validator: validateUserName, trigger: 'blur'}],
    passWord: [{validator: validatePassWord, trigger: 'blur'}],
    validCode: [{required: true, message: '请输入验证码', trigger: 'blur'}]
})

const loginFormRef = reactive()

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            // 注册页面
            if(formType.value){
                const data = await userAuthentication(loginForm)
                if(data.code === 10000){
                    ElMessage.success('注册成功，请登录!')
                }else{
                    ElMessage.error('注册失败!')
                }
            }else{
                // 登录页面
                const data = await login(loginForm)
                if(data.code === 10000){
                    //将token和用户信息缓存到浏览器
                    localStorage.setItem('pz_token', data.data.token)
                    localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo))
                    ElMessage.success('登录成功')
                    // 跳转到首页
                    router.push('/')
                }else{
                    ElMessage.error('登录失败!' + data.msg)
                }
            }
        }
    })
}

</script>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 0;
}
.login-bg{
    min-height: 100vh;
    background: url('@/assets/images/pz-bg.jpg') no-repeat;
    background-size: cover;
    overflow: hidden;
}
.login-container {
  height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  .card-header {
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
  .el-input__suffix-inner {
    cursor: pointer;
  }
}
</style>